//
//  BillVC.m
//  zhiche--delivery
//
//  Created by 王亚陆 on 16/5/26.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "BillVC.h"
#import "BillCell.h"
#import "RootViewController.h"
#import "Common.h"
#import "NullDataView.h"
#import <MJRefresh.h>
#import <Masonry.h>
//#import "WKProgressHUD.h"
@interface BillVC ()<UIGestureRecognizerDelegate>
{
    UIImageView * nav;
    UITableView * table;
    Common * com;
    RootViewController * TabBar;
    NSMutableDictionary * dataSouceDic;
 
    NSMutableArray * dataSouceArr;
    int page;
    int totalPage;
    NullDataView * nullView;
}
@end

@implementation BillVC

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.orderID = [[NSString alloc]init];
        self.monthText = [[NSString alloc]init];
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = GrayColor;
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    
    TabBar = [RootViewController defaultsTabBar];
    dataSouceArr = [[NSMutableArray alloc]init];
    com = [[Common alloc]init];
    
    page = 1;
    totalPage = 1;
    dataSouceDic = [[NSMutableDictionary alloc]init];
    nav = [self createNav:@"账单明细"];
    [self.view addSubview:nav];
    [self createTable];
    
    nullView = [[NullDataView  alloc]initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight - 64) andTitle:@"暂无账单" andImageName:@"形状"];
    nullView.backgroundColor = GrayColor;

}

-(void)createTable{
    table = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, Main_Width, Main_height-64) style:UITableViewStylePlain];
    
    table.backgroundColor = GrayColor;
    [table setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    table.delegate = self;
    table.dataSource = self;
    [table.mj_header beginRefreshing];
    table.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downRefresh)];
    table.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upRefresh)];

    [self.view addSubview:table];
}


-(void)downRefresh{
    
    [table.mj_header endRefreshing];
    [table.mj_footer endRefreshing];
    page = 1;
    [self loadData];
    NSLog(@"刷新");
}

-(void)upRefresh{
    
    if (page!=totalPage) {
        page ++;
        [self loadData];
        [table.mj_footer endRefreshing];

    }else{
        table.mj_footer.state = MJRefreshStateNoMoreData;
    }
    [table.mj_header endRefreshing];
    NSLog(@"加载%d%d",page,totalPage);
    
}

-(void)loadData{

    
    NSString * string = [NSString stringWithFormat:@"%@?pageNo=%d&pageSize=10&billId=%@",Find_BillDetails_Url,page,self.orderID];
    
    [com afPostRequestWithUrlString:string parms:nil finishedBlock:^(id responseObj) {
        
        NSMutableDictionary * dicObj =[NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableContainers error:nil];
        NSMutableArray * arr = [NSMutableArray arrayWithArray:dicObj[@"data"][@"cTurnovers"]];
        
        if ([arr count]>0) {
            [nullView removeFromSuperview];
            if (page == 1) {
                [dataSouceArr removeAllObjects];
                dataSouceArr = arr;
            }else{
                for (int i=0; i<[arr count]; i++) {
                    
                    [dataSouceArr addObject:arr[i]];
                }
            }
        }else{
            [table addSubview:nullView];
        }
        
        [table reloadData];
        totalPage = [dicObj[@"data"][@"page"][@"totalPage"] intValue];

    } failedBlock:^(NSString *errorMsg) {

    }];


}

-(void)viewWillAppear:(BOOL)animated{
    [TabBar setTabBarHidden:YES];
    
    [self loadData];
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    static NSString *str=@"str";
    BillCell  * cell =  [tableView dequeueReusableCellWithIdentifier:str];
    if (cell ==nil) {
        cell = [[BillCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    
//
//                       "id": 274,
//                       "userId": 82,
//                       "userName": "纳尼",
//                       "userType": 40,
//                       "orderId": 1423,
//                       "bussinessId": "CO786744980630167552",
//                       "orderFee": 2023.00,
//                       "orderActPay": 2023.00,
//                       "payType": 10,
//                       "payTypeText": "订单",
//                       "billId": 6320,
//                       "createTime": "2016-10-14 10:45:25",
//                       "status": 20,
//                       "statusText": "已出账单",
//                       "directionText": "支出",
//                       "departName": "山西省大同市",
//                       "receiptName": "山西省长治市",
//                       "carAmount": 1,
//                       "arriveDate": "2016-10-16 00:00:00",
//                       "updateTime": "2016-10-17 16:01:35"
//
    
    cell.priceLabel.text = [NSString stringWithFormat:@"￥%.2f",[dataSouceArr[indexPath.row][@"orderActPay"] floatValue]];
    
    NSString * dateLabel = [NSString stringWithFormat:@"%@",[dataSouceArr[indexPath.row][@"createTime"] substringWithRange:NSMakeRange(0, 10)]];
    cell.dateLabel.text = dateLabel;
    cell.orderLabel.text = [NSString stringWithFormat:@"%@",dataSouceArr[indexPath.row][@"bussinessId"]];
    cell.addressLabel.text = [NSString stringWithFormat:@"%@-%@",dataSouceArr[indexPath.row][@"departName"],dataSouceArr[indexPath.row][@"receiptName"]];
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 58*kHeight;
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return dataSouceArr.count;
//    return 3;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    
    return 1;
}


-(void)createUIAlertController:(NSString*)title
{
    UIAlertController * alert =[UIAlertController alertControllerWithTitle:@"提示" message:title preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * action =[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction * action1 =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alert addAction:action1];
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 43*kHeight;
    
}
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Main_Width, 44*kHeight)];
    view.backgroundColor = WhiteColor;
    UILabel * label = [com createUIlabel:self.monthText andFont:FontOfSize12 andColor:littleBlackColor];
    [view addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(view.mas_left).with.offset(16*kWidth);
        make.centerY.mas_equalTo(view.mas_centerY);
    }];
    
    UIView * viewline = [[UIView alloc]init];
    viewline.backgroundColor = LineGrayColor;
    [view addSubview:viewline];
    [viewline mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(view.mas_right);
        make.bottom.mas_equalTo(view.mas_bottom);
        make.size.mas_equalTo(CGSizeMake(Main_Width, 0.5));
    }];

    
    return view;
}
-(NSString *)backString:(NSString *)string
{
    //    NSString * str = [NSString stringWithFormat:@"%@",string];
    if ([string isEqual:[NSNull null]]) {
        return @"";
    } else {
        return string;
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
